﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Gama.Contract;
using Gama.Service;
using HtmlAgilityPack;

namespace Gama.Service
{
    public class AutoNewsService:IAutoNewsService
    {
        public bool AddOrUpdate(AutoNewsDto dto)
        {
            return SqlService.ExecuteNonQueryWithoutResult("procAutoNewsAddOrUpdate", dto.Key, dto.Source,dto.Value,dto.DateAdded);
        }
        public IList<AutoNewsDto> GetAutoNewsItems()
        {
            return SqlService.ExecuteNonQuery("procGetAutoNewsItems", null).ToList<AutoNewsDto>();
        }
        public IList<NewsLinkDto> GetNewsLinkItems()
        {
            return SqlService.ExecuteNonQuery("procGetNewsLinkItems", null).ToList<NewsLinkDto>();
        }
        public bool GetNewsAndAddToDb()
        {
            foreach (var link in this.GetNewsLinkItems())
            {
                try
                {

                    var doc = new HtmlDocument();
                    var reader = new StreamReader(WebRequest.Create(link.Url).GetResponse().GetResponseStream(),
                                                  Encoding.Default); //put your encoding
                    doc.Load(reader);
                    doc.OptionCheckSyntax = true;
                    doc.OptionFixNestedTags = true;
                    doc.OptionAutoCloseOnEnd = true;
                    doc.OptionOutputAsXml = true;
                    doc.OptionDefaultStreamEncoding = Encoding.Default;

                    var query = from items in doc.DocumentNode.SelectNodes(link.FilterExpression) select items;
                    foreach (var item in query.Where(item => !string.IsNullOrEmpty(item.InnerText)))
                    {
                        AddOrUpdate(new AutoNewsDto()
                            {
                                Key =
                                    string.Format("{0}{1}", link.Url,
                                                  item.Name == "a" ? item.Attributes["href"].Value : string.Empty),
                                Source = link.Url,
                                Value =
                                    Encoding.UTF8.GetString(Encoding.GetEncoding(1252).GetBytes(item.InnerHtml))
                                            .Replace("href=\"", string.Format("href=\"{0}", link.Url)),
                                DateAdded = DateTime.Now
                            });
                    }
                }
                catch (Exception ex)
                {                    
                }
            }

            return true;
        }
    }
}
